package com.szalay.useradmin;

import java.io.File;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;
import org.osgi.service.useradmin.UserAdmin;

/**
 * Group impl.
 */
final class GroupImpl extends UserImpl implements Group {
    private final Dictionary members;
    private final Dictionary requiredMembers;
    private final UserAdmin parent;
    
    /**
     * Create a new group impl.
     * @param name
     * @param storage
     * @param parent 
     */
    GroupImpl(final String name, final File storage, final UserAdmin parent) {
        super(name, storage);
        this.parent = parent;
        members = new WriteBackDictionary(storage, "members");
        requiredMembers = new WriteBackDictionary(storage, "requiredMembers");
    }

    @Override
    public int getType() {
        return GROUP;
    }
    
    @Override
    public boolean addMember(Role role) {
        if (role == null) {
            throw new IllegalArgumentException("Illegal role: null.");
        }
        return (members.put(role.getName(), role.getName()) != null);
    }

    @Override
    public boolean addRequiredMember(Role role) {
        if (role == null) {
            throw new IllegalArgumentException("Illegal role: null.");
        }
        return (requiredMembers.put(role.getName(), role.getName()) != null);
    }

    @Override
    public boolean removeMember(Role role) {
        if (role == null) {
            throw new IllegalArgumentException("Illegal role: null.");
        }
        
        Object o = members.remove(role.getName());
        if (o != null) {
            return true;
        }
        o = requiredMembers.remove(role.getName());
        return (o != null);
    }

    @Override
    public Role[] getMembers() {
        Enumeration keys = members.keys();
        List<Role> result = new ArrayList<Role>(members.size());
        while (keys.hasMoreElements()) {
            String roleName = (String) keys.nextElement();
            result.add(parent.getRole(roleName));
        }
        return result.toArray(new Role[] { });
    }

    @Override
    public Role[] getRequiredMembers() {
        Enumeration keys = requiredMembers.keys();
        List<Role> result = new ArrayList<Role>(requiredMembers.size());
        while (keys.hasMoreElements()) {
            String roleName = (String) keys.nextElement();
            result.add(parent.getRole(roleName));
        }
        return result.toArray(new Role[] { });
    }
}
